package scatter.wxminiapp.rest.service.impl;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaKefuMessage;
import cn.binarywang.wx.miniapp.bean.WxMaMessage;
import cn.binarywang.wx.miniapp.message.WxMaXmlOutMessage;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import scatter.common.rest.validation.DictService;
import scatter.wxminiapp.pojo.po.WxMaMsgReply;
import scatter.wxminiapp.rest.componentext.IMaMsgReplyParser;

import java.util.Map;

/**
 * Created by yangwei
 * Created at 2021/11/22 20:56
 */
@Slf4j
@Order
public class DefaultMaMsgReplyParserImpl implements IMaMsgReplyParser {

    @Autowired
    private DictService dictService;

    @Lazy
    @Autowired
    private WxMaService wxMaService;
    @Override
    public boolean support(WxMaMsgReply reply) {
        return true;
    }

    @Override
    public WxMaXmlOutMessage parse(WxMaMsgReply reply, WxMaMessage wxMessage, Map<String, Object> context, WxMaService wxMaService, WxSessionManager sessionManager) {
        String valueById = dictService.getValueById(reply.getReplyMsgTypeDictId());
        if (StrUtil.isEmpty(valueById)) {
            return null;
        }
        wxMaService.switchoverTo(reply.getAppCode());
        String xmlMsgType = valueById.replace(WxMaMsgReply.WX_MA_PUSH_XML_MSG_TYPE, "");
        switch (xmlMsgType){
            case WxConsts.XmlMsgType.TEXT: {
                try {
                    wxMaService.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content(reply.getReplyContent())
                            .toUser(wxMessage.getFromUser()).build());
                } catch (WxErrorException e) {
                    log.error("微信小程序回复客户消息异常",e);
                }
            }
            default: {
                // 其它暂不支持
                log.warn("不受支持的消息类型 xmlMsgType={}",xmlMsgType);
            }
        }
        return null;
    }
}
